// Plugin para el manejo de tablas

// definición de la función
$.fn.archetypeTree = function(options) {
    // puede recibir un array de parámetros nombrados  
    // invocamos a una función genérica que hace el merge   
    // entre los recibidos y los de por defecto
    var opts = $.extend({}, $.fn.archetypeTree.defaults, options);

    //this.each(showArchetypeTree(opts,this)); 
    return this.each(function(){        
        var dnd = getDND(opts);
        var types = getTypes(opts);
        var plugins = getPlugins(opts);
        var data = getData(opts);        
        
        
        var params = {            
            "themes" : {
                "theme" : "default",                     
                "dots" : opts.showDots,
                "icons" : true
            },
            "types" : {                    
                "types" : types         
                /*"use_data": true */
            },                      
            "crrm" : {
                "move" : {
                    "check_move" : function (m) {
                        return false;
                    }
                }
            },            
            "checkbox":
                {                        
            },
            "contextmenu":{
                "items": function(node)
                {                    
                    var disable = !(node[0].parentNode.parentNode.localName == "div");
                    var options = {
                        // Some key
                        "create": false,
                        "rename": false,
                        "remove": false,
                        "ccp":false,
                        "delete" : {
                            // The item label
                            "label": "Delete",
                            "_disabled":disable,
                            "action": function (obj) {                                 
                                opts.functionEraseable(obj);                                                               
                            }	    	    	   		
                        }		
                    };
                    
                    return options;
                }                
            },
            "dnd":dnd,
            "ui": {
                "initially_select" : opts.selected    
            },            
            "core":{
                "animation":0,
                "html_titles": true
            },
            "rules" : opts.rules,
            "plugins" : plugins
        };
        
        params[opts.dataSource] = data;         
                
        
        $(this).bind("loaded.jstree", function (event, data) {
            if(opts.checkbox && opts.checkedAll){
                $(this).jstree("check_all");                    
            }
        })
        .jstree(params)
        .bind("select_node.jstree", function (event, data) {	            
            opts.onclick(data);
        });        
    });
};

$.fn.archetypeTreeChecked = function(){
    var checked_ids = [];
    
    this.each(function(){        
        $(this).jstree("get_checked",null,true).each(function() {
            if($(this).hasClass("jstree-leaf")){
                checked_ids.push(this.id);
            }
        });
    });
    
    return checked_ids;
}

// definimos los parámetros junto con los valores por defecto de la función
$.fn.archetypeTree.defaults = {
    relativePath:"TemplateDesign-OpenEHRGen",        
    controller:false,
    action:false,
    data:{},
    params:{},
    dnd:false,
    functionDND:function(data){},
    functionDropCheck:function(data) {                         
        return data.o.hasClass("jstree-leaf");
    },
    onclick:function(data){},
    checkbox:false,
    checkedAll: true,
    types:0,
    showDots:true,
    selected:[],
    async:true,
    dataSource:"json_data",
    erasable:false,
    functionEraseable:function(obj){
        obj.parent().parent().remove(); 
    },
    rules:{}
};


/********* Auxiliares ***********/
function getDND(opts){
    var dnd;
    if(opts.dnd != false){    
        dnd = {
            "drop_finish" : function (data) {                 
                /* Esto soluciona que cuando se arrastra una hoja y se usa ajax el icono "desaparezca" */
                $.vakata.dnd.drag_stop();
                opts.functionDND(data);                 
            },                                               
            "drop_check" : function (data) {                            
                 return opts.functionDropCheck(data);            
            },
            "drop_target":opts.dnd,
            "drag_target":false,
            "drag_check" : function (data) {
                return {
                    after : false, 
                    before : false, 
                    inside : false
                };            
            }
            
        };                
    } else {     
        dnd = {
            "drag_target":false,
            "drag_check" : function (data) {
                return {
                    after : false, 
                    before : false, 
                    inside : false
                };            
            }
        };
    }
    
    return dnd;
}

function getTypes(opts){
    var types;
    switch(opts.types){
        case 0:
            types = {                         
                "folder" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/yellow_folder.png"
                    },                    
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "emptyfolder" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/generic_folder.png"
                    },                                     
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "archetype" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/default.png"
                    },         
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                } 
            };
            break;
        case 1:
            types = {
                "action" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/action.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "cluster" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/cluster.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "composition" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/composition.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "count" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/count.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "datetime" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/datetime.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "duration" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/duration.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "element" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/element.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "evaluation" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/evaluation.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },                        
                "instruction" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/instruction.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },                         
                "observation" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/observation.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },                            
                "ordinal" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/ordinal.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },                          
                "quantity" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/quantity.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                }, 
                "section" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/section.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },                                                 
                "slot_cluster" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/slot_cluster.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "structure" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/structure.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },                         
                "text" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/text.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                }, 
                "truefalse" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/truefalse.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                },
                "default" : {
                    "icon" : {
                        "image" : "/" + opts.relativePath + "/js/jstree/themes/default/icons/default.png"
                    },
                    "hover_node" : true,
                    "select_node" : function () {
                        return true;
                    }
                } 
            };
            break;
        default:
            types = {};
            break;              
    }
    
    return types;
}

function getPlugins(opts){
    var plugins = new Array();
    var index = 0;
    
    plugins[index++] = "themes";
    plugins[index++] = "ui";
    plugins[index++] = "types";
    plugins[index++] = "crrm";
    plugins[index++] = "dnd"; 
        
    if(opts.checkbox){
        plugins[index++] = "checkbox";
    }
    
    if(opts.erasable){
        plugins[index++] = "contextmenu"; 
    }
    
    plugins[index] = opts.dataSource;
    
    return plugins;
}

function getData(opts){
    var data;
    
    if(!opts.controller && !opts.action){
        data = {
            "data": opts.data  
        }
    } else {
        data = {
            "ajax" : {
                "url" : "/" + opts.relativePath + "/" + opts.controller + "/" + opts.action,
                "data": opts.params,
                "async":opts.async
            }
        }
    }
    
    return data;
}


